﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using BCCommon.Extensions;
using BCCommon.OAEnums.Reimbursement;
using BCEntity.OA.Reimbursement;
using BCCommon;
namespace BCData.OA.Reimbursement
{
    public class ReimbursementRecordData : IReimbursementRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY = @"SELECT ReimbursementRecordId,
                                              A.ApplyCode,
                                              A.Category,
                                              A.Amount,
                                              A.Content,
                                              A.CompanyId,
                                              A.DepartmentId,
                                              A.DepartmentName,
                                              A.AdminId,
                                              A.AdminName,
                                              A.CreateTime,
                                              A.Status,
                                              A.RemarkFiles,
                                              A.PictureFiles,
                                              A.EditerAdminId,
                                              A.EditerFullName,
                                              A.UpdateTime,
                                              A.VehicleSaleContractNo,A.Address,B.StaffNo From  OA_ReimbursementRecord  A
                                              INNER JOIN DepartmentStaff B ON A.AdminId=B.AdminId
											  INNER JOIN Department C ON A.CompanyId=C.CompanyId";

        public ReimbursementRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        #region 新增操作
        /// <summary>
        /// 新增一批报销信息
        /// </summary>
        /// <param name="entities">报销信息</param>
        /// <returns></returns>
        public async Task<bool> InsertListAsync(List<ReimbursementRecordEntity> entities)
        {
            List<string> sqls = new List<string>();
            List<DynamicParameters> parametersList = new List<DynamicParameters>();
            sqls.AddRange(this.GetInsertReimbursementRecordSqls(entities, out parametersList));
            return await this.databaseContext.Master.TransactionExecuteAsync(sqls, parametersList, databaseContext.Transaction) > 0;
        }

        private List<string> GetInsertReimbursementRecordSqls(List<ReimbursementRecordEntity> entities, out List<DynamicParameters> parametersList)
        {
            List<string> sqls = new List<string>();
            parametersList = new List<DynamicParameters>();
            foreach (var item in entities)
            {
                DynamicParameters parameters = new DynamicParameters();
                sqls.Add(this.GetInsertReimbursementRecordSql(item, out parameters));
                parametersList.Add(parameters);
            }
            return sqls;
        }

        private string GetInsertReimbursementRecordSql(ReimbursementRecordEntity entity, out DynamicParameters parameters)
        {
            string sql =SqlCommands.GetInsertSql("OA_ReimbursementRecord", new string[]
            {
                "ApplyCode", "Category", "Amount", "Content", "CompanyId", "DepartmentId",
                "DepartmentName", "AdminId", "AdminName", "Status", "RemarkFiles", "PictureFiles", "VehicleSaleContractNo"
            });
            parameters = new DynamicParameters();
            parameters.Add("?ApplyCode", entity.ApplyCode, DbType.AnsiString, size: 50);
            parameters.Add("?Category", entity.Category, DbType.AnsiString, size: 100);
            parameters.Add("?Amount", entity.Amount, DbType.Decimal, size: 10);
            parameters.Add("?Content", entity.Content, DbType.AnsiString);
            parameters.Add("?CompanyId", entity.CompanyId, DbType.Int64);
            parameters.Add("?DepartmentId", entity.DepartmentId, DbType.Int32);
            parameters.Add("?DepartmentName", entity.DepartmentName, DbType.AnsiString, size: 50);
            parameters.Add("?AdminId", entity.AdminId, DbType.Int64);
            parameters.Add("?AdminName", entity.AdminName, DbType.AnsiString, size: 50);
            parameters.Add("?Status", entity.Status.ToString(), DbType.AnsiString);
            parameters.Add("?RemarkFiles", entity.RemarkFiles, DbType.AnsiString);
            parameters.Add("?PictureFiles", entity.PictureFiles, DbType.AnsiString);
            parameters.Add("?VehicleSaleContractNo", entity.VehicleSaleContractNo, DbType.AnsiString, size: 50);
            return sql;
        }

        /// <summary>
        /// 根据申请编号获取报销记录信息
        /// </summary>
        /// <param name="applyCode">申请编号</param>
        /// <returns></returns>
        public async Task<ReimbursementRecordEntity> GetEntityByApplyCode(string applyCode)
        {
            string sql = string.Format("{0} Where A.ApplyCode=?ApplyCode", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?ApplyCode", applyCode, DbType.AnsiString, size: 50);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<ReimbursementRecordEntity>(sql, parameters);
        }

        /// <summary>
        /// 新增一条报销信息
        /// </summary>
        /// <param name="entity">报销信息</param>
        /// <returns></returns>
        public async Task<ReimbursementRecordEntity> InsertAsync(ReimbursementRecordEntity entity)
        {
            DynamicParameters parameters = new DynamicParameters();
            string sql = this.GetInsertReimbursementRecordSql(entity, out parameters);
            string querySql = string.Format("{0} {1} Where A.ApplyCode=?ApplyCode", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ReimbursementRecordEntity>(querySql, parameters, databaseContext.Transaction);
        }
        #endregion
        /// <summary>
        /// 更新指定的报销记录状态信息
        /// </summary>
        /// <param name="applyCode">申请单</param>
        /// <param name="modifierName">修改时间</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public async Task<ReimbursementRecordEntity> UpdateStatus(string applyCode, long editerAdminId, string modifierName, ReimbursementApplyStatus status)
        {
            string sql = SqlCommands.GetUpdateSql("OA_ReimbursementRecord", new string[] { "Status", "EditerFullName", "EditerAdminId" }, new string[] { "ApplyCode" });
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Status", status.ToString(), DbType.AnsiString);
            parameters.Add("?EditerFullName", modifierName, DbType.AnsiString);
            parameters.Add("?EditerAdminId", editerAdminId, DbType.Int64);
            parameters.Add("?ApplyCode", applyCode, DbType.AnsiString);
            string querySql = string.Format("{0} {1} Where A.ApplyCode=?ApplyCode", sql, QUERY);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<ReimbursementRecordEntity>(querySql, parameters, databaseContext.Transaction);
        }

        /// <summary>
        /// 分页获取OA报销申请记录(列表)
        /// </summary>
        /// <param name="adminId">当前登录管理员</param>
        /// <param name="departmentName">部门名称</param>
        /// <param name="adminName">员工名称</param>
        /// <param name="start">申请时间开始</param>
        /// <param name="end">申请时间结束</param>
        /// <param name="ascending">是否升序排序</param>
        /// <param name="pageIndex">分页页码</param>
        /// <param name="pageSize">分页页数</param>
        /// <param name="isMyApproved"></param>
        /// <param name="companyId">公司Id</param>
        /// <returns></returns>
        public async Task<(IEnumerable<ReimbursementRecordEntity>, int)> GetListAsync(long adminId, string departmentName, string adminName, DateTime? start, DateTime? end, bool? ascending, int pageIndex, int pageSize, string sortName, bool? isMyApproved, int? companyId)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (companyId.HasValue)
            {
                wheres.Add(" A.CompanyId=?CompanyId");
                parameters.Add("?CompanyId", companyId.Value, DbType.Int64, size: 20);
            }

            if (start.HasValue)
            {
                wheres.Add(" A.CreateTime>=?StartTime");
                parameters.Add("?StartTime", start.Value, DbType.DateTime);
            }
            if (end.HasValue)
            {
                wheres.Add(" A.CreateTime<=?EndTime");
                parameters.Add("?EndTime", end.Value, DbType.DateTime);
            }
            if (isMyApproved.HasValue && isMyApproved.Value)
            {
                wheres.Add(" ?AdminId IN(SELECT ApprovalAdminIds FROM OA_ApplyOrder)");
                parameters.Add("?AdminId", adminId, DbType.Int64);
            }
            if (departmentName.IsNotNull())
            {
                wheres.Add(" A.DepartmentName LIKE CONCAT('%',CONCAT(?DepartmentName,'%'))");
                parameters.Add("?DepartmentName", departmentName, DbType.AnsiString, size: 30);
            }
            if (adminName.IsNotNull())
            {
                wheres.Add(" A.AdminName LIKE CONCAT('%',CONCAT(?AdminName,'%'))");
                parameters.Add("?AdminName", adminName, DbType.AnsiString, size: 30);

            }
            string sql = string.Format(@"{0} {1} GROUP BY A.ApplyCode ORDER BY {2} {3} LIMIT {4},{5}; 
                    SELECT COUNT(1)  FROM  OA_ReimbursementRecord  A {1}",
                    QUERY,
                    wheres.Count > 0 ? string.Format(" WHERE {0}", string.Join(" AND ", wheres)) : string.Empty,
                    !string.IsNullOrWhiteSpace(sortName) ? sortName : "CreateTime",
                    ascending.HasValue ? "ASC" : "DESC",
                    (pageIndex - 1) * pageSize, pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<ReimbursementRecordEntity>(sql, parameters);
        }
    }
}
